// 列表筛选
import { findSubCategoryGoods } from '@/api/category'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
export function useLoadListData () {
  const route = useRoute()
  function toggleSelect (list, self, group) {
    list.forEach(item => {
      item.selected = false
    })
    self.selected = true
    console.log(list, self, group)
    const index = reqParams.attrs.findIndex((item) => item.groupName === group.name)
    if (index > -1) {
      reqParams.attrs.splice(index, 1)
    }
    reqParams.attrs.push({
      groupName: group.name,
      propertyName: self.name
    })
    if (self.id === null) {
      const index = reqParams.attrs.findIndex((item) => item.groupName === group.name)
      if (index > -1) {
        reqParams.attrs.splice(index, 1)
      }
    }
    console.log(reqParams.attrs)
    loadList()
  }
  // 排序功能
  const sortType = [
    { name: '默认排序', value: null },
    { name: '最新商品', value: 'publishTime' },
    { name: '最高人气', value: 'orderNum' },
    { name: '评论最多', value: 'evaluateNum' }
  ]
  const curSortType = ref(null)
  function toggleSort (sortType) {
    curSortType.value = sortType
    reqParams.sortField = sortType
    loadList()
  }
  // 带有多个条件的列表筛选功能
  const reqParams = {
    page: 1, // 页数
    pageSize: 20, // 条数
    categoryId: route.params.id,
    sortField: null, // 排序类别
    attrs: [], // 商品属性
    brandId: null // 品牌名称
  }
  const goodList = ref([])
  async function loadList () {
    const res = await findSubCategoryGoods(reqParams)
    goodList.value = res.result.items
  }
  // 上拉加载
  const isFinited = ref(false)
  const isLoading = ref(true)
  async function loadNext () {
    console.log('执行加载下一页的逻辑')
    isLoading.value = true
    reqParams.page++
    const res = await findSubCategoryGoods(reqParams)
    if (res.result.items.length === 0) {
      isFinited.value = true
    }
    goodList.value = [...goodList.value, ...res.result.items]
    isLoading.value = false
  }
  onMounted(() => {
    loadList()
  })
  return {
    toggleSelect,
    sortType,
    toggleSort,
    curSortType,
    goodList,
    loadNext,
    isFinited,
    isLoading
  }
}
